import {
    request,
    AbstractBookCrawler,
    BasicBook,
    SearchBookResult,
    Book,
    BasicChapter,
    BookCrawlerTest,
    BookSource,
    htmlToString,
    RequestOptions, delayed, removeQuerySelector, removeLinesContaining, getPathFromUrl
} from "../../common/common_node.js";

class BookCrawler extends AbstractBookCrawler {

    async searchBook(keyword, pageNum) {

        const $ = await (await request(`${this.source.searchBaseUrl}/search_${keyword}.html`, new RequestOptions({
            proxy: 'http://127.0.0.1:10809'
        }))).doc();
        const aArr = $("ul.txt-pic-list li a");
        const bookArr = [];
        aArr.each(function () {
            bookArr.push(new BasicBook({
                name: $(this).find(".h1").text(),
                author: $(this).find(".btns .b1").text(),
                path: getPathFromUrl($(this).attr("href")),
            }));
        })

        return new SearchBookResult({
            pageNum: pageNum,
            pages: 1,
            keyword: keyword,
            bookList: bookArr
        });
    }

    async bookDetails(path) {

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        return new Book({
            path: path,
            name: $('[property="og:novel:book_name"]').attr("content"),
            author: $('[property="og:novel:author"]').attr("content"),
            intro: $('[property="og:description"]').attr("content"),
            coverUrl: $('[property="og:image"]').attr("content"),
            type: $('[property="og:novel:category"]').attr("content"),
        });
    }

    async bookCatalog(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        // 找到所有的 dt 元素
        const dtArr = $('.listmain dl dt');

        // 检查 dt 元素的数量
        if (dtArr.length < 2) {
            return [];
        }

        let catalog = [];

        let ddArr = dtArr.eq(1).nextAll('dd');

        ddArr.each((i, e) => {
            catalog.push(new BasicChapter({
                index: i,
                title: $(e).find("a").text(),
                path: path + $(e).find("a").attr("href")
            }));
        })

        return catalog;
    }

    async chapterContent(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        return htmlToString($("#content").html());
    }
}

const source = {
    "id": "free_book_js/21",
    "name": "品书小说网",
    "portalUrl": "https://www.vodtw.com",
    "searchBaseUrl": "https://vodtwcom.allxiaoshuo.com",
    "bookBaseUrl": "https://www.vodtw.com",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true, keyword: "大明国师"
}).run();